# -*-coding:utf-8-*-


import json
import os
import random
import re
import threading
import time
from ctypes import *

import websocket

#引入dll
add_path = os.path.split(os.path.abspath(__file__))[0]+'\\'
dd_dll = CDLL(add_path + 'DD94687.dll')

#DD Initialize
st = dd_dll.DD_btn(0)
if st==1:
    print("DD Initialize OK")
else:
    print("DD Initialize Error")
    exit(101)

timeValue = 1
countValue = 5
count = 1
zhiling = ['#上', '#上3', '#下', '#下3', '#左', '#左3', '#右', '#右3', '#确认', '#返回', '#保存游戏', '#查看背包', '#查看技能', '#跳过']

# 键盘值
keyCodeDec = {
            'esc': 100, 'f1': 101, 'f2': 102, 'f3': 102, 'f4': 104,'f5': 105,'f6': 106,'f7': 107,'f8': 100,'f9': 109,'f10': 110,'f11': 111,'f12': 112,

              '~': 200, '1': 201, '2': 202,'3': 203,'4': 204,'5': 205,'6': 206,'7': 207,'8': 208,'9': 209,'0': 210,'-': 211,'=': 212,'\\': 213,'<-':214,

              'tab': 300, 'q': 301, 'w': 302, 'e': 303, 'r': 304, 't': 305, 'y': 306, 'u': 307, 'i': 308,'o': 309,'p': 310,'[': 311,']': 312,'enter': 313,

              'caps lock': 400,'a': 401, 's': 402, 'd': 403, 'f': 404, 'g': 405, 'h': 406, 'j': 407, 'k': 408, 'l': 409,';': 410,"'": 411,

              'lshift': 500,'z': 501, 'x': 502, 'c': 503, 'v': 504, 'b': 505, 'n': 506, 'm': 507, ',': 508, '.': 509,'/': 510, 'rshift': 511,

              'lctrl': 600,'lwin': 601, 'lalt': 602, 'space': 603, 'ralt': 604, 'rwin': 605, '右': 606, 'rctrl': 607,

              'print': 700,'scroll': 701, 'pause': 702, 'ins': 703, 'home': 704, 'up': 705, 'del': 706, 'end': 707,
              'down': 708, 'up_arrow': 709, 'left_arrow': 710, 'down_arrow': 711, 'right_arrow': 712,

              'x0': 800, 'x1': 801, 'x2': 802, 'x3': 803, 'x4': 804, 'x5': 805, 'x6': 806, 'x7': 807,
              'x8': 808, 'x9': 809, 'num': 810, 'x/': 811, '*': 812, 'x-': 813, '+': 814, 'xenter': 816, 'x.': 816 }


def sendInput(s_input):
    if (s_input in keyCodeDec.keys()):
        ##        if(keyCodeDec[s_input] == 'enter' or keyCodeDec[s_input] == 'esc'):
        ##            k = 0.1
        ##        else:
        k = 0.3
        dd_dll.DD_key(keyCodeDec[s_input], 1)
        time.sleep(k)
        dd_dll.DD_key(keyCodeDec[s_input], 2)



def LookMyStatus():  # 查看自己的状态
    sendInput('s')

def UseSkill():  # 使用技能
    sendInput('esc')
    time.sleep(0.05)
    sendInput('down_arrow')
    time.sleep(0.05)
    sendInput('enter')


def LookBag():  # 查看我的背包
    sendInput('esc')
    time.sleep(0.05)
    sendInput('down_arrow')
    time.sleep(0.05)
    sendInput('down_arrow')
    time.sleep(0.05)
    sendInput('enter')


def SaveGame():  # 保存游戏
    sendInput('esc')
    time.sleep(0.05)
    sendInput('up_arrow')
    time.sleep(0.05)
    sendInput('enter')
    time.sleep(0.05)
    sendInput('enter')
    time.sleep(0.05)
    sendInput('enter')


def Enter():
    sendInput('enter')


def Up():
    sendInput('up_arrow')


def Down():
    sendInput('down_arrow')


def Right():
    sendInput('right_arrow')


def Left():
    sendInput('left_arrow')


def average(what):
    if (what == 'saveGame'):
        SaveGame()
    elif (what == 'lookBag'):
        LookBag()
    elif (what == 'useSkill'):
        UseSkill()
    elif (what == 'tiaoGuo'):
        for i in range(8):
            sendInput('r')
    else:
        sendInput(what)


def Move(i):
    if (i == '#w'):
        Up()
    elif (i == '#s'):
        Down()
    elif (i == '#a'):
        Left()
    elif (i == '#d'):
        Right()


def chuli_1():
    global dic
    move = re.compile(r'#[wasd]([1-9][0-9]?)?')
    while (True):
        if (dic != {}):
            print('dic = ', dic)
            # time.sleep(2)
        for i in list(dic.values()):
            pp = move.match(i)
            if (pp == None):  # 不是方向键
                # 处理其他指令和错误指令
                if (i == '#c'):  # 保存游戏
                    SaveGame()
                elif (i == '#b'):  # 查看背包
                    LookBag()
                elif (i == '#k'):  # 使用技能
                    UseSkill()
                elif (i == '#t'):  # 跳过对话
                    average('tiaoGuo')
                elif (i == '#h'):
                    average('enter')
                elif (i == '#e'):
                    average('esc')
                elif (i == '#A'):  # 战斗状态下，自动普通攻击直至结束
                    average('a')
                elif (i == '#D'):  # 战斗状态下，防御
                    average('d')
                else:  # 非法指令
                    continue
            else:
                s = pp.group()
                totalCount = re.sub("\D", "", s)
                if (totalCount == ''):  # 单纯移动
                    Move(s)
                else:  # 移动加数字
                    m = re.compile(r'(#[wasd])')
                    m = m.match(s)
                    for j in range(int(totalCount)):
                        Move(m.group())
        dic = {}
        time.sleep(0.5)


def chuli():
    global dic
    global timeValue
    global countValue
    global zhiling
    global count
    while (True):
        up_arrow = 0
        down_arrow = 0
        left_arrow = 0
        right_arrow = 0
        enter = 0
        esc = 0
        saveGame = 0
        lookBag = 0
        useSkill = 0
        tiaoGuo = 0
        for i in range(timeValue):  # 每隔timeValue秒计算一次
            time.sleep(1)
            if (len(dic) >= countValue):  # 如果此时消息数大于countValue了，跳出去
                break
        # 5秒后

        d = {}
        # 去掉无关指令
        s = [i for i in dic.keys() if (dic[i] not in zhiling)]  # 找出所有不在指令内的操作
        if (s != []):
            print('无关指令 :', s)
            for i in s:
                dic.pop(i)
        # print('dic为：',dic)
        for i in list(dic.values()):
            if (i == '#上'):
                up_arrow += 1
            elif (i == '#下'):
                down_arrow += 1
            elif (i == '#左'):
                left_arrow += 1
            elif (i == '#右'):
                right_arrow += 1
            elif (i == '#确认'):
                enter += 1
            elif (i == '#返回'):
                esc += 1
            elif (i == '#保存游戏'):
                saveGame += 1
            elif (i == '#查看背包'):
                lookBag += 1
            elif (i == '#查看技能'):
                useSkill += 1
            elif (i == '#跳过'):
                tiaoGuo += 1
                # 保存游戏','#查看背包','#查看技能
        if (up_arrow != 0):
            d['up_arrow'] = up_arrow
        if (down_arrow != 0):
            d['down_arrow'] = down_arrow
        if (left_arrow != 0):
            d['left_arrow'] = left_arrow
        if (right_arrow != 0):
            d['right_arrow'] = right_arrow
        if (enter != 0):
            d['enter'] = enter
        if (esc != 0):
            d['esc'] = esc
        if (saveGame != 0):
            d['saveGame'] = saveGame
        if (lookBag != 0):
            d['lookBag'] = lookBag
        if (useSkill != 0):
            d['useSkill'] = useSkill
        if (tiaoGuo != 0):
            d['tiaoGuo'] = tiaoGuo
        if (d != {}):
            print('最终操作为：', max(d))
            average(max(d))
            dic = {}
#使用dll
def chuli_2():
    global dic
    global timeValue
    global countValue
    global zhiling
    global count
    while (True):
        up_arrow = 0
        down_arrow = 0
        left_arrow = 0
        right_arrow = 0
        enter = 0
        esc = 0
        saveGame = 0
        lookBag = 0
        useSkill = 0
        tiaoGuo = 0
        for i in range(timeValue):  # 每隔timeValue秒计算一次
            time.sleep(1)
        # 5秒后

        d = {}
        # 去掉无关指令
        s = [i for i in dic.keys() if (dic[i] not in zhiling)]  # 找出所有不在指令内的操作
        if (s != []):
            print('无关指令 :', s)
            for i in s:
                dic.pop(i)
        # print('dic为：',dic)
        for i in list(dic.values()):
            if (i == '#上'):
                up_arrow += 1
            elif (i == '#下'):
                down_arrow += 1
            elif (i == '#左'):
                left_arrow += 1
            elif (i == '#右'):
                right_arrow += 1
            elif (i == '#确认'):
                enter += 1
            elif (i == '#返回'):
                esc += 1
            elif (i == '#保存游戏'):
                saveGame += 1
            elif (i == '#查看背包'):
                lookBag += 1
            elif (i == '#查看技能'):
                useSkill += 1
            elif (i == '#跳过'):
                tiaoGuo += 1
                # 保存游戏','#查看背包','#查看技能
        if (up_arrow != 0):
            d['up_arrow'] = up_arrow
        if (down_arrow != 0):
            d['down_arrow'] = down_arrow
        if (left_arrow != 0):
            d['left_arrow'] = left_arrow
        if (right_arrow != 0):
            d['right_arrow'] = right_arrow
        if (enter != 0):
            d['enter'] = enter
        if (esc != 0):
            d['esc'] = esc
        if (saveGame != 0):
            d['saveGame'] = saveGame
        if (lookBag != 0):
            d['lookBag'] = lookBag
        if (useSkill != 0):
            d['useSkill'] = useSkill
        if (tiaoGuo != 0):
            d['tiaoGuo'] = tiaoGuo
        if (d != {}):
            print('最终操作为：', max(d))
            average(max(d))
            dic = {}



def on_message(ws, message):
    global dic
    # print(ws)
    allMsg = json.loads(message)
    dic[allMsg['UserId']] = '#'+allMsg['Content']

def on_error(ws, error):
    # print(ws)
    print(error)


def on_close(ws):
    # print(ws)
    print("### closed ###")


# 打印日志
# websocket.enableTrace(True)
headers = {'roomid': '518519390404'}
ws = websocket.WebSocketApp("ws://127.0.0.1:8001",
                            header=headers,
                            on_message=on_message,
                            on_error=on_error,
                            on_close=on_close)
dic = {}
#随机测试的
# c 保存游戏
# b 查看背包
# k 使用技能
# t 跳过对话
# h enter
# A 战斗状态下，自动普通攻击直至结束
# D 战斗状态下，防御
tmpzhiling = ['#c', '#b', '#k', '#t', '#h', '#e', '#A', '#D', '#w', '#a', '#d', '#s']

def putmsg():
    global dic
    while True:
        dic[random.randint(0,9)] = tmpzhiling[random.randint(0,len(tmpzhiling)-1)]
        time.sleep(0.1)

p1 = threading.Thread(target=chuli_1)
p1.daemon=False
p1.start()

p2 = threading.Thread(target=putmsg)
p2.daemon=False
p2.start()
#ws.run_forever()
